<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <link rel="stylesheet" type="text/css" href="/assets/static/plugin/jquery-confirm/jquery-confirm.min.css"/>
    <link rel="stylesheet" type="text/css" href="/assets/static/admin/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="/assets/static/plugin/bootstrap-multitabs/multitabs.min.css"/>
    <link rel="stylesheet" type="text/css" href="/assets/static/plugin/bootstrap-select/bootstrap-select.css"/>
    <link rel="stylesheet" type="text/css" href="/assets/static/admin/css/style.min.css"/>
</head>

<body>
<div class="container-fluid p-t-15">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header">
                    <div class="card-title">新增网站</div>
                </div>
                <div class="card-body">
                    <div class="alert alert-info" role="alert">注📢: 新增完成后根据网址自动获取标题、Logo、网站描述, 对内容不满可以点击编辑修改呦!</div>
                    <form>
                        <div class="input-group mb-3">
                            <div class="input-group-prepend">
                                <span class="input-group-text">分类</span>
                            </div>
                            <select class="form-control selectpicker col-lg-3" id="category_id" tabindex="null"></select>
                        </div>
                        <div class="form-group">
                            <label>网站地址</label>
                            <small class="help-block">(支持多 URL 添加)</small>
                            <textarea type="text" class="form-control" id="url"
                                      placeholder="必须包含 http:// 或 https://且至少含有1个路径。例如: http://www.test.com/test.html 一行一个呦!"></textarea>
                        </div>
                        <div class="form-group">
                            <label>网站启用</label>
                            <small class="help-block">(网站关闭后将不能展示!)</small>
                            <div class="clearfix">
                                <div class="custom-control custom-radio custom-control-inline">
                                    <input type="radio" id="statusOne" name="customRadioInline" class="custom-control-input" value="0"
                                           checked=""/>
                                    <label class="custom-control-label" for="statusOne">禁用</label>
                                </div>
                                <div class="custom-control custom-radio custom-control-inline">
                                    <input type="radio" id="statusTwo" name="customRadioInline" class="custom-control-input" value="1"/>
                                    <label class="custom-control-label" for="statusTwo">启用</label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>拉取失败时仅保存网址</label>
                            <div class="custom-control custom-switch">
                                <input type="checkbox" class="custom-control-input" id="allowSaveUrlOnFailure">
                                <label class="custom-control-label" for="allowSaveUrlOnFailure">启用</label>
                            </div>
                        </div>

                        <button type="button" id="btnOk" class="btn btn-primary">确认</button>
                        <button type="button" id="btnLoading" class="btn btn-primary" disabled style="display: none">
                            <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
                            执行中...
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="/assets/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/assets/static/admin/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="/assets/static/plugin/bootstrap-maxlength/bootstrap-maxlength.min.js"></script>
<script type="text/javascript" src="/assets/static/plugin/jquery-confirm/jquery-confirm.min.js"></script>
<script type="text/javascript" src="/assets/static/plugin/bootstrap-select/bootstrap-select.min.js"></script>
<script type="text/javascript" src="/assets/static/plugin/bootstrap-select/i18n/defaults-zh_CN.min.js"></script>
<script type="text/javascript" src="/assets/static/plugin/bootstrap-multitabs/multitabs.min.js"></script>
<script type="text/javascript" src="/assets/static/admin/js/httpclient.js"></script>
<script type="text/javascript" src="/assets/static/admin/js/utils.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        AjaxFormNoAsync(
            "GET",
            "/api/admin/category",
            "",
            function () {
            },
            function (data) {
                // 将扁平化数据转换为树形结构
                const treeData = buildTree(data.list);
                // 获取 <select> 元素
                const selectElement = document.getElementById('category_id');
                // 渲染树形结构到 <select>
                renderTreeToSelect(treeData, selectElement, 0, []);
                // 初始化 Bootstrap Select
                $('#tree-select').selectpicker();
            },
            function (response) {
                AjaxError(response);
            }
        );

        $("input#url").maxlength({
            warningClass: "badge badge-info",
            limitReachedClass: "badge badge-warning"
        });

        $('#btnOk').on('click', function () {
            const url = $("#url").val();
            if (url === "") {
                $.alert({
                    title: '温馨提示',
                    icon: 'mdi mdi-alert',
                    type: 'orange',
                    content: '请输入网站链接。',
                });
                return false;
            }
            const failSwitch = $("#allowSaveUrlOnFailure").is(":checked");
            // 获取所有 name 为 customRadioInline 的单选按钮
            const radios = document.querySelectorAll('input[name="customRadioInline"]');
            // 遍历单选按钮，找到选中的值
            let selectedValue;
            radios.forEach(radio => {
                if (radio.checked) {
                    selectedValue = radio.value;
                }
            });

            const postData = {
                category_id: $("#category_id").val(),
                url: url,
                is_used: selectedValue === "1",
                fail_switch: failSwitch,
            };

            AjaxForm(
                "POST",
                "/api/admin/site",
                postData,
                function () {
                    $("#btnOk").hide();
                    $("#btnLoading").show();
                },
                function (data) {
                    // 动态生成失败 URL 的 HTML 内容
                    let failURLsHTML = '';
                    if (data.failURLs && data.failURLs.length > 0) {
                        failURLsHTML += '<div class="card-title">以下 URL 创建失败：</div>';
                        data.failURLs.forEach(function (url) {
                            failURLsHTML += `
			                            <div class="alert alert-warning" role="alert">
			                                <a href="#!" class="alert-link">${url}</a>
			                            </div>
			                        `;
                        });
                    } else {
                        failURLsHTML = '<div class="alert alert-info" role="alert">无失败 URL。</div>';
                    }
                    // 弹窗内容
                    const content = `
			                    <div class="card">
			                        <header class="card-header">
			                            <div class="card-title">成功创建：${data.successCount} 条, 失败创建：${data.failCount} 条</div>
			                        </header>
			                        <div class="card-body">
			                            ${failURLsHTML}
			                        </div>
			                    </div>
			                `;
                    $.alert({
                        title: '操作成功',
                        icon: 'mdi mdi-check-decagram',
                        type: 'green',
                        content: content,
                        buttons: {
                            okay: {
                                text: '关闭',
                                action: function () {
                                    if (data.failCount > 0) { // 如果有失败的 URL，则显示执行中按钮
                                        $("#btnLoading").hide();
                                        $("#btnOk").show();
                                    } else { // 如果没有失败的 URL，则直接跳转到网站列表页
                                        location.href = "/admin/site";
                                    }
                                }
                            }
                        }
                    });
                },
                function (response) {
                    $("#btnLoading").hide();
                    $("#btnOk").show();
                    AjaxError(response);
                }
            );
        });
    })
</script>
</body>
</html>
